package com.sofun.ai.config.rag;

import dev.langchain4j.community.web.search.searxng.SearXNGWebSearchEngine;
import dev.langchain4j.web.search.WebSearchEngine;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 联网搜索引擎配置
 * @author:wjl
 * @see:
 * @since:
 * @date:2025-03-07-9:52
 * @description:com.study.langchain4jspringboot.ai.websearch
 * @version:1.0
 */
@Configuration
public class WebSearchConfiguration {

    @Value("${searxng.base-url}")
    String baseUrl;

    @Value("${searxng.engines}")
    String engine;

    /**
     * 构建searxng联网搜索引擎
     * @return WebSearchEngine实例
     */
    @Bean
    public WebSearchEngine searXNGWebSearchEngine() {
        System.out.println("初始化SearXNG搜索引擎 - baseUrl: " + baseUrl + ", engine: " + engine);
        
        Map<String, Object> additionalParams = new HashMap<>();
        // 添加引擎参数
        if (StringUtils.hasText(engine)) {
            additionalParams.put("engines", engine);
        } else {
            // 如果没有配置引擎，使用默认引擎
            additionalParams.put("engines", "bing");
        }
        
        // 添加语言参数
        additionalParams.put("language", "zh-CN");
        
        // 添加搜索结果数量参数
        additionalParams.put("count", 10);
        
        // 添加超时参数 (毫秒)
        additionalParams.put("timeout", 10000);
        
        // 添加分类参数
        additionalParams.put("categories", "general");
        
        return SearXNGWebSearchEngine.builder()
                .baseUrl(baseUrl)
                .optionalParams(additionalParams)
                .logRequests(true)
                .logResponses(true)
                .build();
    }
}
